<template>
	<div :class="['address-input',state]">
		<label class="address-label">
			<span class="address-label-text">{{label}}</span>
			<slot>
				<input class="address-label-input" :type="type" v-bind="$attrs" @input="changeInput($event)"
				       @blur="validator"/>
			</slot>
			<div class="address-border"></div>
		</label>
	</div>
</template>

<script>
	export default {
		name: "Input",
		props: {
			value: {
				type: [String, Number]
			},
			label: {
				type: String,
				default: 'label'
			},
			type: {
				type: String,
				default: 'text',
				validator(value) {
					return ['text', 'tel', 'number', 'email'].indexOf(value) > -1;
				}
			},
			rules: {
				type: Function
			},
			required: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				state: 'default'
			}
		},
		methods: {
			changeInput(e) {
				this.$emit('input', e.target.value);
			},
			validator() {
				if (this.required) {
					if (this.value === '') {
						this.state = 'error';
						return;
					}
				}
				if (!this.rules) {
					this.state = 'default';
				} else {
					let state = this.rules(this.value);
					this.state = state ? 'success' : 'error';
				}
			}
		}
	}
</script>
